const express = require('express');
const bcrypt = require('bcryptjs');
const { body, validationResult } = require('express-validator');
const { query } = require('../config/database');
const { generateToken, authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 用户登录
router.post('/login', [
  body('username').notEmpty().withMessage('用户名不能为空'),
  body('password').notEmpty().withMessage('密码不能为空')
], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    const { username, password } = req.body;

    // 查找用户
    const [user] = await query(
      'SELECT * FROM users WHERE username = ? AND status = "active"',
      [username]
    );

    if (!user) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 生成token
    const token = generateToken(user.id);

    // 更新最后登录时间
    await query(
      'UPDATE users SET last_login = NOW() WHERE id = ?',
      [user.id]
    );

    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
        name: user.name
      }
    });

  } catch (error) {
    console.error('登录错误:', error);
    const msg = /db|database/i.test(error.message) ? '数据库错误' : '服务器错误';
    res.status(500).json({ message: msg });
  }
});

// 用户注册
router.post('/register', [
  body('username').isLength({ min: 3 }).withMessage('用户名至少3个字符'),
  body('password').isLength({ min: 6 }).withMessage('密码至少6个字符'),
  body('email').isEmail().withMessage('邮箱格式不正确'),
  body('name').notEmpty().withMessage('姓名不能为空')
], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    const { username, password, email, name } = req.body;

    // 检查用户名是否已存在
    const [existingUser] = await query(
      'SELECT id FROM users WHERE username = ? OR email = ?',
      [username, email]
    );

    if (existingUser) {
      return res.status(400).json({ message: '用户名或邮箱已存在' });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 12);

    // 创建用户
    const result = await query(
      'INSERT INTO users (username, password, email, name, role, status, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())',
      [username, hashedPassword, email, name, 'user', 'active']
    );

    const userId = result.insertId;
    const token = generateToken(userId);

    res.status(201).json({
      message: '注册成功',
      token,
      user: {
        id: userId,
        username,
        email,
        name,
        role: 'user'
      }
    });

  } catch (error) {
    console.error('注册错误:', error);
    const msg = /db|database/i.test(error.message) ? '数据库错误' : '服务器错误';
    res.status(500).json({ message: msg });
  }
});

// 获取当前用户信息
router.get('/me', authenticateToken, async (req, res) => {
  try {
    const [user] = await query(
      'SELECT id, username, email, name, role, status, created_at, last_login FROM users WHERE id = ?',
      [req.user.id]
    );

    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    res.json({ user });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    const msg = /db|database/i.test(error.message) ? '数据库错误' : '服务器错误';
    res.status(500).json({ message: msg });
  }
});

// 修改密码
router.put('/change-password', [
  authenticateToken,
  body('currentPassword').notEmpty().withMessage('当前密码不能为空'),
  body('newPassword').isLength({ min: 6 }).withMessage('新密码至少6个字符')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ 
        message: '输入验证失败', 
        errors: errors.array() 
      });
    }

    const { currentPassword, newPassword } = req.body;

    // 获取用户当前密码
    const [user] = await query(
      'SELECT password FROM users WHERE id = ?',
      [req.user.id]
    );

    // 验证当前密码
    const isValidPassword = await bcrypt.compare(currentPassword, user.password);
    if (!isValidPassword) {
      return res.status(400).json({ message: '当前密码错误' });
    }

    // 加密新密码
    const hashedNewPassword = await bcrypt.hash(newPassword, 12);

    // 更新密码
    await query(
      'UPDATE users SET password = ? WHERE id = ?',
      [hashedNewPassword, req.user.id]
    );

    res.json({ message: '密码修改成功' });
  } catch (error) {
    console.error('修改密码错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 退出登录
router.post('/logout', authenticateToken, (req, res) => {
  // 在实际应用中，可以将token加入黑名单
  res.json({ message: '退出登录成功' });
});

module.exports = router; 